package com.sinevil.tcpTrans.utils.fileTrans.entity;

import com.sinevil.tcpTrans.entity.json.FileInfoJson;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.SneakyThrows;

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;

/**
 * @Classname FileTransInfo
 * @Description 文件信息类，记录文件相关信息，如文件MD5标识，文件大小和已接收字节数等
 * @Version 1.0.0
 * @Date 2024/12/12 22:16
 * @Created by sinevil
 */
@Data
@Builder
@AllArgsConstructor
public class FileTransInfo {
    protected String name;
    protected String MD5;
    protected Path path;
    protected RandomAccessFile raf;
    protected FileChannel channel;
    /**
     * 文件大小
     */
    protected long fileSize;
    /**
     * 已写入大小
     */
    protected long writtenByte;
    /**
     * 切片个数
     */
    protected int slice;
    /**
     * 已完成切片数
     */
    protected int completedSlice;
    protected SocketChannel socketChannel;
    public boolean isBig;
    /**
     * 标志文件传输状态
     * 1 创建任务，未开始
     * 2 任务进行中
     * 3 任务失败
     * 4 任务完成
     */
    public int mark;


    /**
     *
     * @param MD5 MD5
     * @param fileSize 文件大小（字节）
     */
    public FileTransInfo(String MD5, long fileSize) {
        this.MD5 = MD5;
        this.fileSize = fileSize;
    }
    public FileTransInfo(String MD5, RandomAccessFile raf, long fileSize) {
        this.MD5 = MD5;
        this.raf = raf;
        this.fileSize = fileSize;
    }


    /**
     *
     * @param MD5 MD5
     * @param fos 文件输出流
     * @param fileSize 文件大小（字节）
     */
    public FileTransInfo(String MD5, Path path, RandomAccessFile raf, long fileSize) {
        this.MD5 = MD5;
        this.path = path;
        this.raf = raf;
        this.fileSize = fileSize;
    }


    @Override
    public boolean equals(Object o) {
        if (o instanceof FileInfoJson){
            FileInfoJson fileInfoJson = (FileInfoJson) o;
            return this.MD5.equals(fileInfoJson.getMD5()) && this.fileSize == fileInfoJson.getFileSize();
        }
        return false;
    }
    public void completeASlice(){
        this.completedSlice++;
    }

    public boolean isComplete(){
        return this.slice == this.completedSlice;
    }

    @SneakyThrows
    public void releaseResource(){
        this.raf.close();
    }
}